# application/mapper/system/dict.py
from application.extensions.databases import db
from application.extensions.logging import system_logger
from application.models.system.dict_data import SysDictData
from typing import List, Dict, Any


class DictDataMapper:
    """字典数据访问层"""

    @staticmethod
    def get_dict_data_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> tuple:
        """
        分页获取字典数据列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: (字典数据列表, 总数)
        """
        query = db.session.query(SysDictData).filter(SysDictData.del_flag == 0)

        # 添加查询条件
        if conditions:
            if conditions.get("dictLabel"):
                query = query.filter(
                    SysDictData.dict_label.like(f"%{conditions['dictLabel']}%")
                )
            if conditions.get("dictType"):
                query = query.filter(
                    SysDictData.dict_type.like(f"%{conditions['dictType']}%")
                )
            if conditions.get("status"):
                query = query.filter(SysDictData.status == conditions["status"])

        # 获取总数
        total = query.count()

        # 分页查询
        offset = (page_num - 1) * page_size
        dict_data_list = (
            query.order_by(SysDictData.dict_code).offset(offset).limit(page_size).all()
        )

        return dict_data_list, total

    @staticmethod
    def get_dict_data_by_type(dict_type: str) -> List[SysDictData]:
        """
        根据字典类型获取字典数据列表
        :param dict_type: 字典类型
        :return: 字典数据列表
        """
        return (
            db.session.query(SysDictData)
            .filter(SysDictData.dict_type == dict_type)
            .filter(SysDictData.del_flag == 0)  # 只查询未被逻辑删除的记录
            .order_by(SysDictData.dict_sort)
            .all()
        )

    @staticmethod
    def create_dict_data(dict_data:SysDictData) -> List[SysDictData]:
        """
        创建字典数据
        :param dict_data: 字典数据对象
        :return: 创建后的字典数据对象
        """
        db.session.add(dict_data)
        db.session.commit()
        return dict_data
    

    @staticmethod
    def update_dict_data(dict_data: SysDictData) -> SysDictData:
        """
        更新产品型号
        :param product_model: 产品型号对象
        :return: 更新后的产品型号对象
        """
        db.session.commit()
        return dict_data

    @staticmethod
    def get_dict_data_by_code(dict_code: int) -> SysDictData:
        """
        根据ID获取字典数据
        :param dict_code: 字典数据ID
        :return: 字典数据对象
        """
        return (
            db.session.query(SysDictData)
            .filter(SysDictData.dict_code == dict_code)
            .first()
        )

    

    

    @staticmethod
    def batch_delete_dict_data(dict_code: list) -> int:
        """
        批量逻辑删除绕组
        :param dict_code: 绕组ID列表
        :return: 删除的记录数
        """
        try:
            # 执行批量逻辑删除，将 del_flag 设置为 1
            updated_count = db.session.query(SysDictData).filter(
                SysDictData.dict_code.in_(dict_code),
                SysDictData.del_flag == 0  # 只更新未删除的记录
            ).update(
                {SysDictData.del_flag: 1},
                synchronize_session=False
            )
            
            db.session.commit()
            return updated_count
        except Exception as e:
            db.session.rollback()
            system_logger.error(f"批量逻辑删除字典失败: {e}")
            raise e